package com.lap.auth.domain.project.service;

import com.lap.auth.domain.project.Project;
import com.lap.auth.domain.project.repository.ProjectRepository;
import com.lap.auth.domain.shared.errors.UserError;
import com.lap.framework.exception.BizException;
import java.util.Optional;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class ProjectValidator {

  private final ProjectRepository projectRepository;

  public Project assertProjectExists(Integer id) {
    return projectRepository
        .findById(id)
        .orElseThrow(() -> BizException.newBiz(UserError.PROJECT_NOT_FOUND));
  }

  public void validateContextUnique(Project project, boolean isUpdate) {
    Optional<Project> optional = projectRepository.findByContext(project.getContext());
    optional.ifPresent(
        p -> {
          if (!isUpdate || !p.getId().equals(project.getId())) {
            BizException.interrupt(UserError.PROJECT_EXISTS);
          }
        });
  }
}
